package com.zuikaku.nettydemo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Main {


    public static void main(String[] args){
        NioEventLoopGroup eventLoopGroup = null;
        try {
            //1.创建线程组
            eventLoopGroup = new NioEventLoopGroup();
            //2.创建客户端启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3.设置客户端启动助手线程组
            bootstrap.group(eventLoopGroup)
                    //4.指定通信channel类型
                    .channel(NioSocketChannel.class)
                    //5.创建channel初始化器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //6.完成channel初始化，指定编解码器以及自定义handler
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            //todo 添加客户端自定义handler
                            socketChannel.pipeline().addLast(new MyNettyClientHandler());
                        }
                    });
            //7.连接目标服务器，以同步的方式，且获得返回的channelFuture对象
           ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7788).sync();
           //8.设置channelFuture对象在未来以同步方式关闭
           channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
